package com.example.administrator.activity.Homework.Homework7;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class NoteSQLitehelp extends SQLiteOpenHelper {
    private SQLiteDatabase database;

    /**
     * 数据库操作类：
     * 1.必须重写的方法
     * 构造方法（建库）、onCreate（建表语句）、onUPdagrade（修改表结构）
     * 2.增加方法
     *  @param context
     *
     */
    public NoteSQLitehelp(@Nullable Context context) {
        super(context, "note.sql",null,1);
        /**
         * 初始化
         */
        database = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table note(id integer primary key autoincrement,content text,time text)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    /**
     * 获取系统当前时间
     */
    public String getTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        return simpleDateFormat.format(date);
    }

    /**
     * 保存数据，将记录保存在SQLite
     *
     * @return
     */
    public boolean insertDate(String content, String time) {
        String sql = "insert into note(content,time) values(?,?)";
        database.execSQL(sql, new Object[]{content, time});
        return true;
    }

    public boolean delete(int id) {
        String sql = "delete from note where id=?";
        database.execSQL(sql, new Object[]{id});
        return true;
    }

    public boolean update(int id, String content, String time){
        String sql="update note set content=?,time=? where id=?";
        database.execSQL(sql,new Object[]{content,time,id});
        return true;
    }

    public ArrayList<NoteBean> query(){
        ArrayList<NoteBean> arrayList=new ArrayList<NoteBean>();
        String sql="select * from note order by time desc";
        Cursor cursor=database.rawQuery(sql,null);
        while (cursor.moveToNext()){

            /**
             * 从游标中取出数据
             * 封装在NoteBean对象中
             * 添加到Arraylist
             */
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            String content=cursor.getString(cursor.getColumnIndex("content"));
            String time=cursor.getString(cursor.getColumnIndex("time"));

            NoteBean noteBean=new NoteBean(id,content,time);
            arrayList.add(noteBean);
        }
        cursor.close();
        return arrayList;
    }


}
